<template>
  <div class="flex flex-col h-screen">
    <header
      class="h-14 bg-header-background text-button-text-color flex items-center px-6 text-xl font-bold justify-between">
      <div class="flex items-center gap-4">
        <span>VeloAdmin 后台管理系统</span>
        <!-- 菜单收缩/展开按钮 -->
        <button
          @click="toggleSidebar"
          class="text-button-text-color border-0 bg-transparent hover:primary-text-hover pt-1.5 transition cursor-pointer"
          :title="sidebarCollapsed ? '展开菜单' : '收起菜单'">
          <span v-if="sidebarCollapsed" class="i-solar:plaaylist-minimalistic-bold w-6 h-6" />
          <span v-else class="i-solar:menu-dots-bold w-6 h-6" />
        </button>
      </div>
      <div class="flex items-center gap-4 text-base font-normal">
        <el-popover placement="bottom-start" trigger="click">
          <template #reference>
            <div
              class="flex items-center gap-2 bg-primary/60 px-3 py-1 rounded-lg cursor-pointer hover:bg-primary-hover/60 transition-colors">
              <img
                src="https://api.dicebear.com/7.x/miniavs/svg?seed=admin"
                class="w-6 h-6 rounded-full border-2 border-white shadow"
                alt="头像" />
              <div class="flex flex-col leading-tight">
                <span class="font-bold text-sm">Admin</span>
                <span class="text-xs text-secondary-text"></span>
              </div>
            </div>
          </template>
          <div class="flex flex-col py-1 bg-white dark:bg-gray-800">
            <router-link
              to="/profile/info"
              class="px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-blue-50 dark:hover:bg-gray-700 transition-colors flex items-center gap-2 no-underline">
              <span class="i-solar:user-bold-duotone w-4 h-4" />
              个人信息
            </router-link>
            <router-link
              to="/profile/password"
              class="px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-blue-50 dark:hover:bg-gray-700 transition-colors flex items-center gap-2 no-underline">
              <span class="i-solar:key-bold-duotone w-4 h-4" />
              修改密码
            </router-link>
            <div
              class="px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-blue-50 dark:hover:bg-gray-700 transition-colors flex items-center gap-2 cursor-pointer"
              @click="handleLogout">
              <span class="i-solar:logout-bold-duotone w-4 h-4" />
              退出登录
            </div>
          </div>
        </el-popover>
        <span class="px-2 py-1 bg-primary/40 rounded text-xs text-button-text-color">超级管理员</span>
        <!-- 消息按钮 -->
        <button class="bg-transparent border-0 relative hover:bg-primary/40 p-2 rounded transition">
          <span class="i-solar:bell-bold-duotone w-5 h-5" />
          <span class="absolute top-1 right-1 w-3 h-3 bg-danger rounded-full border-2 border-primary"></span>
        </button>
        <!-- 主题切换组件 -->
        <ThemeSwitch />
      </div>
    </header>
    <div class="flex flex-1">
      <aside
        :class="['transition-all duration-300', sidebarCollapsed ? 'w-26' : 'w-66']"
        class="bg-aside-background p-4 border-r border-border-color shadow-sm overflow-auto"
        style="height: calc(100vh - 56px)">
        <el-menu
          :default-active="activeMenuPath"
          class="w-full border-0"
          :collapse="sidebarCollapsed"
          :unique-opened="true"
          router>
          <template v-for="item in filteredMenuItems">
            <el-sub-menu v-if="item.children" :index="String(item.label)" :key="String(item.label)">
              <template #title>
                <font-awesome-icon :icon="item.icon" class="w-4 h-4" />
                <span class="ml-2">{{ item.label }}</span>
              </template>
              <el-menu-item v-for="sub in item.children" :index="String(sub.path!)" :key="String(sub.path!)">
                <font-awesome-icon :icon="sub.icon" class="w-4 h-4" />
                <span class="ml-2">{{ sub.label }}</span>
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item v-else-if="item.path" :index="String(item.path)" :key="String(item.path)">
              <font-awesome-icon :icon="item.icon" class="w-4 h-4" />
              <span class="ml-2">{{ item.label }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </aside>
      <section class="flex-1 bg-content-background p-8 pt-2 overflow-hidden" style="height: calc(100vh - 56px)">
        <!-- 页面标签栏 -->
        <div
          class="flex gap-2 mb-2 select-none rounded-xl px-4 py-2 border border-border-color shadow-[0_2px_12px_0_var(--colors-secondary-shadow)] relative overflow-x-auto flex-nowrap scrollbar-thin"
          style="scrollbar-width: thin; scrollbar-color: #cbd5e1 #f1f5f9">
          <div
            v-for="(tag, idx) in tags"
            :key="tag.path"
            class="flex items-center px-3 py-1 rounded-lg cursor-pointer group transition-all relative shadow-sm shadow-secondary-shadow hover:shadow-md min-w-0 max-w-xs"
            :class="
              route.path.startsWith(tag.path)
                ? 'text-primary-text font-bold shadow-md scale-[1.04] ring-2 ring-primary/30 bg-theme-primary-light'
                : 'text-primary-text hover:bg-primary-hover/20 hover:text-secondary-text'
            "
            @click="handleTagClick(tag.path)"
            @contextmenu="openContextMenu($event, tag, idx)">
            <span v-if="tag.affix" class="mr-1 text-primary-text i-solar:home-2-bold-duotone w-4 h-4" />
            <span class="truncate max-w-[120px]">{{ tag.label }}</span>
            <span
              v-if="!tag.affix"
              class="ml-1 text-xs opacity-60 group-hover:opacity-100 i-solar:close-circle-bold-duotone w-4 h-4 cursor-pointer"
              @click.stop="handleTagClose(idx)" />
            <div
              v-if="idx < tags.length - 1"
              class="w-px h-5 bg-gradient-to-b from-divider-light via-divider to-divider-light mx-2 opacity-60"></div>
          </div>
          <!-- 自定义右键菜单浮层 -->
          <div
            v-if="contextMenu.visible"
            class="fixed shadow-[0_2px_8px_var(--colors-secondary-shadow)] min-w-[120px] p-y-[4px] bg-dropdown-background rounded-[6px]"
            :style="{
              left: contextMenu.x + 'px',
              top: contextMenu.y + 'px',
              zIndex: 99999,
              borderRadius: '6px',
            }"
            @contextmenu.prevent>
            <ul class="py-1 list-none">
              <li
                class="px-3 py-1.5 text-sm cursor-pointer flex items-center gap-1 hover:bg-dropdown-hover-background transition-colors"
                @click="handleContextCommand('refresh')">
                <span class="mr-1 i-solar:refresh-bold-duotone w-4 h-4" />
                刷新
              </li>
              <li
                class="px-3 py-1.5 text-sm cursor-pointer flex items-center gap-1 hover:bg-dropdown-hover-background transition-colors"
                :class="{ 'opacity-50 pointer-events-none': contextMenu.tag?.affix }"
                @click="!contextMenu.tag?.affix && handleContextCommand('close')">
                <span class="mr-1 i-solar:close-circle-bold-duotone w-4 h-4" />
                关闭当前
              </li>
              <li
                class="px-3 py-1.5 text-sm cursor-pointer flex items-center gap-1 hover:bg-dropdown-hover-background transition-colors"
                :class="{ 'opacity-50 pointer-events-none': tags.length <= 2 }"
                @click="tags.length > 2 && handleContextCommand('closeOthers')">
                <span class="mr-1 i-solar:minus-circle-bold-duotone w-4 h-4" />
                关闭其它
              </li>
              <li
                class="px-3 py-1.5 text-sm cursor-pointer flex items-center gap-1 hover:bg-dropdown-hover-background transition-colors"
                :class="{ 'opacity-50 pointer-events-none': contextMenu.idx === tags.length - 1 }"
                @click="contextMenu.idx !== tags.length - 1 && handleContextCommand('closeRight')">
                <span class="mr-1 i-solar:round-arrow-right-bold-duotone w-4 h-4" />
                关闭右侧
              </li>
              <li
                class="px-3 py-1.5 text-sm cursor-pointer flex items-center gap-1 hover:bg-dropdown-hover-background transition-colors"
                :class="{ 'opacity-50 pointer-events-none': tags.length <= 1 }"
                @click="tags.length > 1 && handleContextCommand('closeAll')">
                <span class="mr-1 i-solar:close-circle-line-duotone w-4 h-4" />
                关闭全部
              </li>
            </ul>
          </div>
        </div>
        <router-view v-slot="{ Component }" style="height: calc(100vh - 140px)" class="overflow-auto">
          <keep-alive :include="cachedComponentNames">
            <component
              :is="Component"
              :key="`${String(route.name)}-${route.fullPath}-${refreshedKeys[String(route.name)] || 0}`" />
          </keep-alive>
        </router-view>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { transformPermissionsToMenu } from '@/utils/menu'
import ThemeSwitch from '@/components/ThemeSwitch.vue'

const router = useRouter()

const route = useRoute()
const userStore = useUserStore()

// 侧边栏折叠状态
const sidebarCollapsed = ref(false)

// 动态菜单数据
const menuItems = ref<
  Array<{
    path?: string
    label: string
    icon: string
    children?: Array<{
      path?: string
      label: string
      icon: string
    }>
  }>
>([])

// 标签页数据
const tags = ref<
  Array<{
    path: string
    name: string
    label: string
    affix?: boolean
  }>
>([
  {
    path: '/index',
    name: 'index',
    label: '首页',
    affix: true,
  },
])

// 右键菜单状态
const contextMenu = ref<{
  visible: boolean
  x: number
  y: number
  tag: (typeof tags.value)[0] | null
  idx: number
}>({
  visible: false,
  x: 0,
  y: 0,
  tag: null,
  idx: -1,
})

// 刷新计数，用于强制刷新组件
const refreshedKeys = ref<Record<string, number>>({})

// 获取用户权限并构建菜单
async function fetchUserMenu() {
  try {
    // 等待权限树加载
    if (!userStore.permissions) {
      await new Promise((resolve) => {
        const unwatch = watch(
          () => userStore.permissions,
          (newVal) => {
            if (newVal) {
              unwatch()
              resolve(null)
            }
          },
        )
      })
    }

    // 转换为菜单结构
    menuItems.value = transformPermissionsToMenu(userStore.permissions || [])
  } catch (error) {
    console.error('获取菜单失败:', error)
  }
}

// 过滤显示的菜单
const filteredMenuItems = computed(() => {
  return menuItems.value
})

// 缓存的组件名称
const cachedComponentNames = computed(() => tags.value.map((tag) => tag.name))

// activeMenuPath 计算属性
const activeMenuPath = computed(() => {
  // 只高亮一级菜单项和子菜单项
  const match = menuItems.value
    .flatMap((item) => (item.children ? item.children : item))
    .find((i) => i.path && route.path.startsWith(`${i.path}`))
  return match ? match.path : '/index'
})

// 切换侧边栏
function toggleSidebar() {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 处理标签点击
function handleTagClick(path: string) {
  router.push(path)
}

// 处理标签关闭
function handleTagClose(idx: number) {
  const tag = tags.value[idx]
  if (tag.affix) return

  // 如果关闭的是当前激活的标签
  if (route.path.startsWith(tag.path)) {
    // 跳转到前一个标签
    if (idx > 0) {
      router.push(tags.value[idx - 1].path)
    } else if (tags.value.length > 1) {
      router.push(tags.value[idx + 1].path)
    } else {
      router.push('/dashboard')
    }
  }

  tags.value.splice(idx, 1)
}

// 打开右键菜单
function openContextMenu(event: MouseEvent, tag: (typeof tags.value)[0], idx: number) {
  event.preventDefault()
  contextMenu.value = {
    visible: true,
    x: event.clientX,
    y: event.clientY,
    tag,
    idx,
  }

  // 点击其他地方关闭右键菜单
  const closeMenu = () => {
    contextMenu.value.visible = false
    document.removeEventListener('click', closeMenu)
  }

  setTimeout(() => {
    document.addEventListener('click', closeMenu)
  }, 0)
}

// 处理右键菜单命令
function handleContextCommand(command: string) {
  const { tag, idx } = contextMenu.value
  if (!tag) return

  switch (command) {
    case 'refresh':
      // 刷新当前标签
      refreshedKeys.value[String(route.name)] = (refreshedKeys.value[String(route.name)] || 0) + 1
      break
    case 'close':
      handleTagClose(idx)
      break
    case 'closeOthers':
      // 保留首页和当前标签
      tags.value = tags.value.filter((t, i) => t.affix || i === idx)
      break
    case 'closeRight':
      // 关闭当前标签右侧的标签
      tags.value = tags.value.slice(0, idx + 1)
      break
    case 'closeAll':
      // 只保留首页
      tags.value = tags.value.filter((t) => t.affix)
      router.push('/dashboard')
      break
  }

  contextMenu.value.visible = false
}

const handleLogout = async () => {
  userStore.logout()
}

// 监听路由变化，更新标签
watch(
  () => route.path,
  (newPath) => {
    // 检查是否已经存在该标签
    if (!tags.value.some((tag) => tag.path === newPath)) {
      // 查找路由对应的名称
      const routeLabel = router.getRoutes().find((r) => r.path === newPath)?.meta.title
      const routeName = router.getRoutes().find((r) => r.path === newPath)?.name as string
      tags.value.push({
        path: newPath,
        name: routeName,
        label: typeof routeLabel === 'string' ? routeLabel : newPath,
      })
    }
  },
  { immediate: true },
)

onMounted(() => {
  fetchUserMenu()
})

// 监听用户登录状态变化，重新获取菜单
watch(
  () => userStore.isLoggedIn,
  (newVal) => {
    if (newVal) {
      fetchUserMenu()
    } else {
      ;``
      menuItems.value = []
    }
  },
)
</script>

<style scoped>
.router-link-active,
.router-link-exact-active {
  text-decoration: none !important;
}

.no-underline {
  text-decoration: none !important;
}

ul.list-none {
  list-style: none;
  padding-left: 0;
  margin: 0;
}
</style>
